package com.azdebugit.list.arraylist.testsize;

import org.springframework.util.StopWatch;

import java.nio.file.WatchService;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class ArrayListRemove {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            list.add("shanghai");
            list.add("shanghai");
            list.add("guangzhou");
            list.add("shenzhen");
            list.add("shanghai");
            list.add("hangzhou");
            list.add("shanghai");
            list.add("beijing");
            list.add("shanghai");
            list.add("shanghai");
            list.add("guangzhou");
            list.add("shenzhen");
            list.add("shanghai");
            list.add("hangzhou");
            list.add("shanghai");
        }

//        print(list);
        System.out.println("\n");
        removeSetRepeat(list); // 9ms  25ms
//        removeStrRepeat(list);  //19ms  78ms
        System.out.println("\n");
//        removeRowRepeat(list);  //9ms  24ms
    }

    private static void print(List<String> list) {
        System.out.print("item:");
        for (String item : list) {
            System.out.print(item+"：");
        }
    }
    /*
     * 正确 StringBuilder去重 14万条数据19ms，140万条数据 78ms
     */
    public static void removeStrRepeat(List<String> list){
        StopWatch sw = new StopWatch();
        sw.start();
        StringBuilder stringBuilder = new StringBuilder("x");
        for(int i = list.size() - 1; i >= 0; i--){
            String item = list.get(i);
            if(item == null || stringBuilder.toString().contains(item)){
                list.remove(i);
                continue;
            }
            stringBuilder.append(item).append("x");
        }
        print(list);
        sw.stop();
        System.out.println("----：" + sw.getTotalTimeMillis()+"ms");
    }
    /*
     * 正确 ArrayList去重 14万条数据9ms，140万条数据 24ms
     */
    public static void removeRowRepeat(List<String> list){
        StopWatch sw = new StopWatch();
        sw.start();
        List<String> rowx = new ArrayList<>();
        for(int i = list.size() - 1; i >= 0; i--){
            String item = list.get(i);
            if(item == null || rowx.contains(item)){
                list.remove(i);
                continue;
            }
            rowx.add(item);
        }
        print(list);
        sw.stop();
        System.out.println("----：" + sw.getTotalTimeMillis()+"ms");
    }
    /*
     * 正确 HashSet去重 14万条数据9ms，140万条数据 25ms
     */
    public static void removeSetRepeat(List<String> list){
        StopWatch sw = new StopWatch();
        sw.start();
        Set<String> set = new HashSet<>(list);
        print(new ArrayList<>(set));
        sw.stop();
        System.out.println("----：" + sw.getTotalTimeMillis()+"ms");
    }


}